package net.cloudsun.tree.huffman;

import net.cloudsun.tree.binary.BinaryNode;

/**
 * 赫夫曼树节点
 *
 * @author Ryan
 * @since 1.1
 */
public class HuffmanNode extends BinaryNode<Integer> {

    /**
     * 0或者1
     */
    private String code;
    /**
     * 代表的字母
     */
    private Character element;
    public HuffmanNode(Integer integer) {
        super(integer);
    }

    @Override
    public void add(BinaryNode<Integer> newNode) {
        if (this.getLeft() == null) {
            setLeft(newNode);
            ((HuffmanNode)newNode).setCode("0");
        } else if (this.getRight() == null) {
            setRight(newNode);
            ((HuffmanNode)newNode).setCode("1");
        } else {
            throw new IllegalArgumentException("节点已满");
        }
    }

    public Character getElement() {
        return element;
    }

    public void setElement(Character element) {
        this.element = element;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getFullCode() {
        final StringBuilder builder = new StringBuilder();
        for (HuffmanNode parent = this; parent != null; parent = (HuffmanNode) parent.parent) {
            if (parent.code != null) {
                builder.insert(0, parent.code);
            }
        }
        return builder.toString();
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(value.toString());
        if (element != null) {
            stringBuilder.append("(").append(element).append(")");
        }
        if(code != null) {
            stringBuilder.append('[').append(getFullCode()).append(']');
        }
        return stringBuilder.toString();
    }
}
